<?php

namespace backend\modules\wechat\controllers;

use backend\controllers\AdminController;
use common\components\Helper;
use maxwen\easywechat\Wechat;
use Yii;
use common\models\wechat\WechatMenu;
use backend\modules\wechat\models\WechatMenuSearch;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * MenuController implements the CRUD actions for WechatMenu model.
 */
class MenuController extends AdminController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all WechatMenu models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new WechatMenuSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single WechatMenu model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new WechatMenu model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new WechatMenu();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing WechatMenu model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing WechatMenu model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the WechatMenu model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return WechatMenu the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = WechatMenu::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }



    public function actionPubMenu()
    {


        $menus = WechatMenu::find()->select('id,name,type,trigger,parentid')->where('parentid=0')->asArray()->all();
        foreach ($menus as $key => $row){
            $sbutton = (new Query())->select('name,type,trigger')->from(WechatMenu::tableName())->where('parentid=:id',[':id'=>$row['id']])->all();
            foreach($sbutton as $k => $r){
                if($sbutton[$k]['type'] == 'view'){
                    if(!Helper::isDomain($sbutton[$k]['trigger'])) {
                        return $this->dialog('菜单  “'.$sbutton[$k]['name'].'”  设置的连接有误','warning','/wechat/menu/index');
                    }
                    $sbutton[$k]['url'] = $sbutton[$k]['trigger'];
                }else{
                    $sbutton[$k]['key'] = $sbutton[$k]['trigger'];
                }
                unset($sbutton[$k]['trigger']);
            }

            $menus[$key]['sub_button'] = $sbutton;
            if(empty($sbutton)){
                if($menus[$key]['type'] == 'view'){
                    $menus[$key]['url'] = $menus[$key]['trigger'];
                }else{
                    $menus[$key]['key'] = $menus[$key]['trigger'];
                }
            }

            unset($menus[$key]['id'],$menus[$key]['parentid'],$menus[$key]['trigger']);
        }

        $menu = \Yii::$app->wechat->menu;
        $result = $menu->add($menus);
        return $this->dialog('菜单设置成功','success','/wechat/menu/index');
    }




}
